<?php
function insertPointPenilaian($bapID){
	$CI =& get_instance();
	$CI->load->model(array('bap_model','perbuatan_model','perbuatan_detil_model',
		'penilaian_model','nilai_model'));
	
	$bapData = (array) $CI->bap_model->select_by_id($bapID)->row();
	$perbData = (array) $CI->perbuatan_model->select_by_id($bapData['perb_id'])->row();
	$deperbData = $CI->perbuatan_detil_model->select_by_id($bapData['perb_id']);
	
	foreach($deperbData->result_array() as $row){
		//hitung sudah brapa kali melakukan detachiev yang sama
		$count = $CI->penilaian_model->count(
			$row['kary_id'],
			$row['kary_jbt_id'],
			$row['detachiev_id']);
		
		//hitung point-nya
		$point = (array)$CI->nilai_model->getNilai($row['detachiev_id'], $count+1);
		$tgl_aktif = $bapData['bap_status_change'];
		
		$CI->penilaian_model->insert(array(
//			'point_id'=>,
			'bap_id'=>$bapID,
			'perb_id'=>$perbData['perb_id'],
			'kary_id'=>$row['kary_id'],
			'kary_jbt_id'=>$row['kary_jbt_id'],
			'detachiev_id'=>$row['detachiev_id'],
			'point_tgl_aktif'=>$tgl_aktif,
			'point_count'=>$count+1,
			'point_point'=>$point['nilai_point']
		));
		
		updateRanking($row['kary_id'], $tgl_aktif, $point['nilai_point']);
	}
}

/**
 * update nilai point pada table ranking
 * @param $kary_id
 * @param $periode
 * @param $point
 */
function updateRanking($kary_id, $periode, $point){
	$CI =& get_instance();
	$CI->load->model(array('ranking_model'));
	
	$CI->ranking_model->updatePoint($kary_id, $periode, $point);
	
	//revalidate rank_ranking, urutkan kembali
	$result = $CI->ranking_model->selectByPeriode($periode, 'rank_point desc');
	$CC = 1;
	foreach($result->result_array() as $row){
		$CI->ranking_model->update(array('rank_id'=>$row['rank_id']),array('rank_ranking'=>$CC++));
	}
}